package com.opendeepsearch;

import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.openai.OpenAiChatModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

/**
 * Standalone utility to test KIMI API connectivity
 */
public class KimiApiTester {
    private static final Logger logger = LoggerFactory.getLogger(KimiApiTester.class);
    
    public static void main(String[] args) {
        System.out.println("=== KIMI API Connectivity Tester ===");
        
        // Check environment variables
        String apiKey = System.getenv("KIMI_API_KEY");
        if (apiKey == null || apiKey.trim().isEmpty()) {
            System.err.println("❌ KIMI_API_KEY environment variable not set");
            System.err.println("Please set: export KIMI_API_KEY=\"your_key_here\"");
            System.exit(1);
        }
        
        System.out.println("✅ KIMI_API_KEY found");
        
        try {
            // Test API connection
            System.out.println("🔍 Testing KIMI API connection...");
            
            ChatModel chatModel = OpenAiChatModel.builder()
                    .apiKey(apiKey)
                    .baseUrl("https://api.moonshot.cn/v1")
                    .modelName("kimi-k2-0711-preview")
                    .build();
            
            // Simple connectivity test
            String testPrompt = "Hello! Please respond with 'KIMI API is working correctly' if you receive this message.";
            ChatResponse response = chatModel.chat(dev.langchain4j.data.message.UserMessage.from(testPrompt));
            
            System.out.println("✅ API Connection Successful!");
            System.out.println("Response: " + response.aiMessage().text());
            
            // Run additional tests
            runDetailedTests(chatModel);
            
            // Interactive mode
            runInteractiveMode(chatModel);
            
        } catch (Exception e) {
            System.err.println("❌ API Test Failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static void runDetailedTests(ChatModel chatModel) {
        System.out.println("\n=== Running Detailed Tests ===");
        
        try {
            // Test 1: Simple factual question
            System.out.println("🔍 Test 1: Simple factual question");
            ChatResponse response1 = chatModel.chat(dev.langchain4j.data.message.UserMessage.from("What is 2+2?"));
            System.out.println("   Response: " + response1.aiMessage().text());
            
            // Test 2: Chinese language support
            System.out.println("🔍 Test 2: Chinese language support");
            ChatResponse response2 = chatModel.chat(dev.langchain4j.data.message.UserMessage.from("你好，请用中文回答"));
            System.out.println("   Response: " + response2.aiMessage().text().substring(0, Math.min(50, response2.aiMessage().text().length())) + "...");
            
            // Test 3: Longer response
            System.out.println("🔍 Test 3: Research-style question");
            ChatResponse response3 = chatModel.chat(dev.langchain4j.data.message.UserMessage.from("Briefly explain artificial intelligence in one sentence"));
            System.out.println("   Response: " + response3.aiMessage().text());
            
            System.out.println("✅ All tests passed!");
            
        } catch (Exception e) {
            System.err.println("❌ Test failed: " + e.getMessage());
        }
    }
    
    private static void runInteractiveMode(ChatModel chatModel) {
        System.out.println("\n=== Interactive Mode ===");
        System.out.println("Type 'exit' to quit");
        
        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                System.out.print("\nYou: ");
                String input = scanner.nextLine();
                
                if (input.trim().equalsIgnoreCase("exit")) {
                    System.out.println("Goodbye!");
                    break;
                }
                
                if (input.trim().isEmpty()) {
                    continue;
                }
                
                try {
                    long startTime = System.currentTimeMillis();
                    ChatResponse response = chatModel.chat(dev.langchain4j.data.message.UserMessage.from(input));
                    long endTime = System.currentTimeMillis();
                    
                    System.out.println("KIMI (" + (endTime - startTime) + "ms): " + response.aiMessage().text());
                    
                } catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                }
            }
        }
    }
}